package com.walle.ak47.commons.utils;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.walle.ak47.commons.jaxrs.cxf.header.SecureHeaderHolder;

@Service
public class SecureHanderChecker {
	
	private static final Logger LOG = LoggerFactory.getLogger(SecureHanderChecker.class);

	public boolean isEfficacious(String xAuthHander, String privateKey )
	{
		//rsa解密
		String sAuthenticate;
		try {
			sAuthenticate = RSASecurityUtil.decrypt( xAuthHander, privateKey );
		} catch (Exception e) {
			e.printStackTrace();
			return false ;
		}
		//校验header合法性
		String[] param = StringUtils.split(sAuthenticate, ",");
		if (param == null || param.length != 3
				|| StringUtils.isBlank(param[0])
				|| StringUtils.isBlank(param[1])
				|| StringUtils.isBlank(param[2])) 
		{
			LOG.error( "无效的X-AUTH-HEADER" );
			return false ;
		}
		String authenToken = AESCodec.decode(param[0]);
		if(!authenToken.equals(param[1]))
		{
			LOG.error( "无效的systemId");
			return false ;
		}
		
		long begin = Long.parseLong(param[2]);
		long now = System.currentTimeMillis();
		int second = 10 ;
		if(StringUtils.isNotBlank(PropertiesReader.getWebConfig("second"))){
			second = Integer.parseInt(PropertiesReader.getWebConfig("second"));
		}
		
		long timeGap =  (now-begin)/1000 ;
		if ( Math.abs(timeGap) > second )
		{
			LOG.error( "客户端时间错误,Server date is {},client date is {}", DateUtils.dateToStr( new Date(now)) , DateUtils.dateToStr( new Date(begin)) );
			return false ;
		}
			
		SecureHeaderHolder.getHeader().getAttrs().put( "token", param[0]) ;

		return true ;
	}
 
}
